package zhongbo.javaweb.instagram.web.util;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;

/**
 * 说明：Junit Test 单元测试工具类
 *
 * @author 钟波notebook
 * @see <a href="https://www.iteye.com/blog/cavenfeng-1716561">检测是否在运行JUnit单元测试</a>
 * @since 2020年04月03日 星期五 01:06:22
 */
@Slf4j
public class JunitUtil {

    /**
     * 判断是否运行于Junit单元测试中
     *
     * @return true-是;false-否
     */
    public static boolean isRunningInTest() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        List<StackTraceElement> stackList = Arrays.asList(stackTrace);

        for (int i = 0; i < stackList.size(); i++) {
            Object aStackList = stackList.get(i);
            String stackString = aStackList.toString();
            // for junit 4
            if (stackString.lastIndexOf("junit.runners") > -1) {
                log.info("running in JunitTest case. stack: {} i: {}", stackString, i);
                return true;
            }
            // 新版 junit 5
            if (stackString.lastIndexOf("junit.platform") > -1) {
                log.info("running in JunitTest case. stack: {} i: {}", stackString, i);
                return true;
            }
        }
        return false;
    }
}
